package com.wulwu.permission.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wulwu.permission.model.UserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description Jwt 工具类
 * @Author Major
 * @Date 2020/12/4 13:49
 */
public class JwtUtils {

    public static final String TOKEN_HEADER = "access_token";

    public static final String TOKEN_PREFIX = "WuxbBearer_";

    private static final String SUBJECT = "wuxb";

    private static final long EXPIRITION = 7 * 24 * 60 * 60 * 1000;

    private static final String APPSECRET_KEY = "wuxb_secret";

    private static final String PERMISSION_CLAIMS = "permissions";

    private static final String USER_NAME = "username";

    /**
     * @Description 创建 token
     * @Author Major
     * @Date 2020/12/4 17:54
     * @Param userEntity:
     * @Return java.lang.String
     */
    public static String generateJsonWebToken(UserEntity userEntity){
        String token = Jwts
                .builder()
                .setSubject(SUBJECT)
                .claim(PERMISSION_CLAIMS, userEntity.getAuthorities())
                .claim(USER_NAME, userEntity.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
                .signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact();
        return token;
    }

    public static Claims getClaims(String token){
        try {
            final Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
            return claims;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Description 获取用户名
     * @Author Major
     * @Date 2020/12/4 17:48
     * @Param token: 
     * @Return java.lang.String
     */ 
    public static String getUsername(String token){
        Claims claims = getClaims(token);
        if (Objects.nonNull(claims)){
            return claims.get(USER_NAME).toString();
        }
        return null;
    }

    /**
     * @Description 获取权限
     * @Author Major
     * @Date 2020/12/4 17:54
     * @Param token:
     * @Return java.util.List<org.springframework.security.core.authority.SimpleGrantedAuthority>
     */
    public static List<SimpleGrantedAuthority> getPermission(String token){
        Claims claims = getClaims(token);
        if (Objects.nonNull(claims)){
            try {
                String permissionJsonStr = JSON.toJSONString(claims.get(PERMISSION_CLAIMS));
                List<SimpleGrantedAuthority> grantedAuthorities = JSONArray.parseArray(permissionJsonStr, SimpleGrantedAuthority.class);
                return grantedAuthorities;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    public static boolean isExpiration(String token) {
        Claims claims = getClaims(token);
        if (Objects.nonNull(claims)){
            Date expiration = claims.getExpiration();
            System.out.println(new Date().before(expiration));
        }
        return false;
    }


    public static void main(String[] args) {
        isExpiration("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ3dXhiIiwicGVybWlzc2lvbnMiOlt7ImF1dGhvcml0eSI6ImFkZE1lbWJlciJ9XSwidXNlcm5hbWUiOiJ4aWFvaGUiLCJpYXQiOjE2MDc1Njc1NzEsImV4cCI6MTYwODE3MjM3MX0.3SbaocvdHEMLtPVCeTYcT0JrJag4uVJiZ0gEpV1Fnc0");
    }
}
